{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%matplotlib notebook\n",
    "%matplotlib widget\n",
    "%run helpers/ensure_print.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.widgets as mwidgets\n",
    "from matplotlib.gridspec import GridSpec\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mpg = pd.read_csv('data/auto-mpg.data', delim_whitespace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_slider(fig, data, \n",
    "                x_data='model_year',\n",
    "                y_data='acceleration',\n",
    "                c_data='horsepower' ,\n",
    "                s_data='displacement'):\n",
    "    h_data = 'mpg'\n",
    "    # use gridspec to build un-evenly split axes, make what will be the \n",
    "    # histogram axes 1/3 the height of the main axes.\n",
    "    gs = GridSpec(3, 1, figure=fig)\n",
    "    ax1 = fig.add_subplot(gs[0:2, :])\n",
    "    ax2 = fig.add_subplot(gs[2, :])\n",
    "    \n",
    "    # histogram the the mgp\n",
    "    hist = ax2.hist(h_data, data=data, bins='auto') \n",
    "    ax2.set(xlabel=h_data, ylabel='N')\n",
    "    # set up a text label to publish updates to\n",
    "    range_label = ax2.annotate('', (1, 1), \n",
    "                               ha='right', va='top', \n",
    "                               xycoords='axes fraction', \n",
    "                               xytext=(-4, -4), \n",
    "                               textcoords='offset points') \n",
    " \n",
    "    # plot the data with some alpha and extra think marker edges\n",
    "    sc = ax1.scatter(x_data, y_data, c=c_data, s=s_data, data=data, \n",
    "                     alpha=.5, linewidth=3) \n",
    "    ax1.set(xlabel=x_data, ylabel=y_data)\n",
    "    \n",
    "    # produce a legend with the unique colors from the scatter \n",
    "    legend1 = ax1.legend(*sc.legend_elements(), \n",
    "                    loc=\"upper left\", title=c_data,  \n",
    "                   ncol=3) \n",
    "    ax1.add_artist(legend1) \n",
    "     # produce a legend with a cross section of sizes from the scatter \n",
    "    handles, labels = sc.legend_elements(prop=\"sizes\", alpha=0.6) \n",
    "    legend2 = ax1.legend(handles, labels, loc=\"lower right\", title=s_data, ncol=3) \n",
    "    \n",
    "   \n",
    "    def mark_markers(low, high):\n",
    "     \n",
    "        base_ec = sc.get_facecolors() \n",
    "        ec = np.array(base_ec) \n",
    "        mask = (low < data[h_data]) & (data[h_data] < high) \n",
    "        mask = mask.values \n",
    "        ec[mask, :3] = [1, 0, 0] \n",
    "        sc.set_edgecolor(ec) \n",
    "        range_label.set_text(f'showing {low:.2f} < {h_data} < {high:.2f}')\n",
    "        fig.canvas.draw_idle()\n",
    "         \n",
    "    slider = mwidgets.SpanSelector(ax2, mark_markers, 'horizontal', useblit=True, span_stays=True)\n",
    "    fig.tight_layout()\n",
    "    return slider \n",
    " \n",
    "s = make_slider(plt.figure(figsize=(9, 10)), mpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exercise: Port the picker from the titanic to this example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.gcf().canvas.layout.height='8in'\n",
    "plt.gcf().canvas.layout.width='9in'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
